<?php

namespace app\api\controller\cron;
use app\admin\model\CouponRecord;
use app\admin\model\Order;
use app\admin\model\order\Operations;
use app\api\service\OrderService;
use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Base;
use think\Request;

/**
 * 计划任务 - 优惠券
 */
class Coupon extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /**
     * 优惠券到期失效
     * https://你的域名/addons/tongcheng/cron.Coupon/expire
     */
    public function expire()
    {
        $time  = time();
        $count = \app\admin\model\Coupon::where('status', 1)
            ->where('end_time', '<', $time)
            ->update(['status' => 2]);// 2:已过期

        $count += CouponRecord::where('status', 0)
            ->where('expire_time', '<', $time)
            ->update(['status' => 2]);// 2:已过期

        $this->success('请求成功', $count);
    }

    public function order_lose(){
       $order= Order::where('order_status','=',0)->where('expire_pay_time','lt',time())->select();
        foreach ($order as $row) {
            $result = Order::where('id',$row['id'])->where('order_status','=',0)->update(['order_status'=>3,'memo'=>'超时未支付','refund_time'=>time()]);
            if($result>0){
                $service = new OrderService();
                $service->return_co_av($row['id']);
                // 订单操作记录
                Operations::create([
                    'order_id' => $row['id'],
                    'action' => '取消订单',
                    'user_id' => $row['user_id'],
                    'description' => '超时取消订单',
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);

            }
        }
        $this->success('请求成功', []);
    }

}
